package cn.com.zcode.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.StringWriter;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

public class PdfUtil {
	public static String read(String pdfFile) {
		return read(pdfFile, 1, Integer.MAX_VALUE, false);
	}

	public static String read(File pdfFile) {
		return read(pdfFile, 1, Integer.MAX_VALUE, false);
	}

	public static String read(String pdfFile, int startPage, int endPage, boolean sort) {

		String result = null;
		PDDocument document = null;
		try {
			document = PDDocument.load(pdfFile);
			result = getContext(document, startPage, endPage, sort);
		} catch (FileNotFoundException fe) {
			fe.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeDocument(document);
		}
		return result;
	}

	private static String getContext(PDDocument document, int startPage, int endPage, boolean sort) throws IOException {

		PDFTextStripper stripper = new PDFTextStripper();
		stripper.setSortByPosition(sort);
		stripper.setStartPage(startPage);
		stripper.setEndPage(endPage);

		StringWriter sw = new StringWriter();
		stripper.writeText(document, sw);
		return sw.toString();
	}

	public static String read(File pdfFile, int startPage, int endPage, boolean sort) {
		String result = null;
		PDDocument document = null;
		try {
			document = PDDocument.load(pdfFile);
			result = getContext(document, startPage, endPage, sort);
		} catch (FileNotFoundException fe) {
			fe.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeDocument(document);
		}
		return result;
	}

	private static void closeDocument(PDDocument document) {
		if (document != null) {
			try {
				document.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String getText(String pdfname, String objfile) {
		String qtext = null;
		try {
			File file = new File(objfile);
			if (!file.exists()) {
				file.createNewFile();
			} else {
				qtext = ObjectUtil.readObject(objfile, String.class);
			}

			if (qtext == null) {
				File qfile = new File(PdfUtil.class.getResource(pdfname).toURI());
				qtext = PdfUtil.read(qfile);
				ObjectUtil.storeObject(objfile,   qtext);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qtext;

	}

	
}
